#include "../pch.h"

#include "REFDecoderReplacementFallback.h"

namespace BFX
{
//////////////////////////////////////////////////////////////////////////////

REFDecoderReplacementFallbackBuffer::REFDecoderReplacementFallbackBuffer(REFDecoderReplacementFallback* pFallback)
{
	BFX_ASSERT(pFallback != NULL);
	m_chReplacement = pFallback->GetReplacementChar();
	m_nFallbackCount = -1;
}

REFDecoderReplacementFallbackBuffer::~REFDecoderReplacementFallbackBuffer()
{
}

bool REFDecoderReplacementFallbackBuffer::Fallback(SequenceT<BYTE> bytesUnknown, int iOffset)
{
	// We expect no previous fallback in our buffer
	BFX_ENSURE1(m_nFallbackCount < 1, "Recursive fallback not allowed.");

	// Go ahead and get our fallback
	m_nFallbackCount = 1;

	return true;
}

// Get next character
UCHAR REFDecoderReplacementFallbackBuffer::GetNextChar()
{
	// We want it to get < 0 because == 0 means that the current/last character is a fallback
	// and we need to detect recursion.  We could have a flag but we already have this counter.
	m_nFallbackCount --;

	// Do we have anything left? 0 is now last fallback char, negative is nothing left
	if (m_nFallbackCount < 0)
		return 0;

	return m_chReplacement;
}

// Back up a character
bool REFDecoderReplacementFallbackBuffer::MovePrevious()
{
	// Back up one, only if we just processed the last character (or earlier)
	if (m_nFallbackCount >= -1)
	{
		m_nFallbackCount++;
		return true;
	}
	// Return false 'cause we couldn't do it.
	return false;
}
// Returns how many chars left in this fallback?
int REFDecoderReplacementFallbackBuffer::GetRemaining()
{
	// Our count is 0 for 1 character left.
	return (m_nFallbackCount < 0) ? 0 : m_nFallbackCount;
}

//////////////////////////////////////////////////////////////////////////////

REFDecoderReplacementFallback::REFDecoderReplacementFallback(UCHAR chReplacement)
{
	m_chReplacement = chReplacement;
}

REFDecoderReplacementFallback::~REFDecoderReplacementFallback()
{
}

REFDecoderFallbackBuffer* REFDecoderReplacementFallback::CreateFallbackBuffer()
{
	REFDecoderReplacementFallbackBuffer* pFallbackBuffer = new REFDecoderReplacementFallbackBuffer(this);
	pFallbackBuffer->Autorelease();
	return pFallbackBuffer;
}

}	//	namespace BFX
